
var sVpmnMebInfo = null;//缓存业务量数据
var WsGetActRecord = null;//缓存营销活动数据
var sPhConMoreQry = null;//缓存个人余额基础数据 TODO test
var intervalTime = 300;
var marketingDetail = {};
var loginNo = getParamValue("EmpCode");
var phone = getParamValue("phone");

var getContent = function(title,value){
  return '<div class="am-g">'
      +  '<div class="am-u-sm-5 am-u-md-4 am-u-lg-3 right-style">'+title+'</div>'
      +  '<div class="am-u-sm-7 am-u-md-8 am-u-lg-9 left-style">'+value+'</div>'
      +  '</div>';
};

var check = function(str){
  if(str && str != "0"){
    return str;
  }else{
    return "";
  }
};

var checkNull = function(str){
  if(str){
    return str;
  }else{
    return "无";
  }
};

/*
自定义模板规则：业务量
*/
Handlebars.registerHelper('businessVolume', function(item) {

  var out = '';
  if(item instanceof Object){

    sVpmnMebInfo = item;

    out += getContent("客户名称：",checkNull(item.CUST_NAME))+"<hr/>";
    out += getContent("品牌套餐：",checkNull(item.SM_NAME))+"<hr/>";
    out += getContent("手机号码：",checkNull(item.PHONE_NO))+"<hr/>";
    out += getContent("V网名称：",checkNull(item.GRP_NAME))+"<hr/>";
    out += getContent("V网短号：",checkNull(item.SHORT_NO))+"<hr/>";
    out += getContent("V网套餐：",checkNull(item.PRCID_NAME))+"<hr/>";
    out += getContent("V网剩余分钟数：",checkNull(item.REM_TIME));
  }
  
  return out;
});

/*
自定义模板规则：营销活动列表
*/
Handlebars.registerHelper('marketingActivity', function(items,options) {
  var itemArr = new Array();
  if(items instanceof Array){
    itemArr = items;
  }else if(items instanceof Object){
    itemArr.push(items);
  } 
  
  var out = '';
  var l=itemArr.length;
  if(l > 0){
    WsGetActRecord = itemArr;

    for(var i=0; i<l; i++) {
      //var item = options.fn(items[i]);
      var item = itemArr[i];
      marketingDetail[item.ORDER_ID + "-" + i]=item;
      //{order_id:"01815031200034497",act_name:"全省数据业务营销活动-Y15Q全省数据业务营销活动-Y15Q全省数据业务营销活动-Y15Q",oper_time:"2015-0-3-",act_type:"胡玉蓉",act_model:"ADS0",desc:"该号未办理保底或已取消保底"};
      out += '<li class="am-g am-list-item-desced am-list-item-thumbed am-list-item-thumb-right" id="'+item.ORDER_ID+"-"+i+'" onclick="toDetail(this.id)">'
          + '<div class="am-u-sm-12 am-u-md-12 am-u-lg-12">'
          + '<div class="am-text-truncate">'+checkNull(item.MEANS_NAME)+'</div>'
          + '<div class="am-text-xs" style="color:#999999;">'+checkNull(item.OPER_NAME)+'('+checkNull(item.OPER_DATE)+')</div>'
          + '</div>'
          // + '<div class="am-u-sm-2 am-u-md-1 am-u-lg-1 am-text-right am-padding-top-sm">'
          // + '<i class="fa fa-chevron-right am-icon-xs" aria-hidden="true"></i>'
          // + '</div>'
          + '</li>';
    }
  }else{
    out = "查无参加过的营销活动！";
  }

  return out;
});

/*
自定义模板规则：营销活动详情
*/
Handlebars.registerHelper('marketingDetail', function(item) {
  var out = '';
  if(item instanceof Object){
    out += getContent("流水号：",checkNull(item.ORDER_ID))+"<hr/>";
    out += getContent("活动名称：",checkNull(item.MEANS_NAME))+"<hr/>";
    out += getContent("操作时间：",checkNull(item.OPER_DATE))+"<hr/>";
    out += getContent("活动类型：",checkNull(item.OPER_NAME))+"<hr/>";
    out += getContent("活动模块：",checkNull(item.ACT_ID))+"<hr/>";
    if(!check(item.baodijine) && !check(item.baodikaishi) && !check(item.baodijiesu)){
      out += getContent("保底说明：","该号未办理保底或己取消保底")+"<hr/>";
    }else{
      out += getContent("保底金额：",item.baodijine)+"<hr/>";
      out += getContent("办理时间：",checkNull(item.banlishijian))+"<hr/>";
      out += getContent("保底开始时间：",checkNull(item.baodikaishi))+"<hr/>";
      out += getContent("保底结束时间：",checkNull(item.baodijiesu))+"<hr/>";
    }
    out += '<div class="am-g">'
        +  '<div class="am-u-sm-12 am-u-md-12 am-u-lg-12 am-btn am-btn-primary am-btn-sm" onclick="toList()">返回</div>'
        +  '</div>';
  }else{
    out = "无营销活动详情数据！";
  }
  
  return out;
});

/*
自定义模板规则：个人余额
*/
Handlebars.registerHelper('baseInfo', function(item) {
  var out = '';
  if(item instanceof Object){
    sPhConMoreQry = item;
    
    out += getContent("客户名称：",checkNull(item.CUST_NAME))+"<hr/>";
    out += getContent("手机号码：",checkNull(phone))+"<hr/>";
    out += getContent("归属地：",checkNull(item.REGION_NAME))+"<hr/>";
    out += getContent("套餐类型：",checkNull(item.PROD_PRC_NAME))+"<hr/>";
    out += getContent("未出账账单：",item.UNBILL_FEE)+"<hr/>";
    out += getContent("当前余额：",item.REMAIN_FEE)+"<hr/>";
    // out += getContent("总欠费：",checkNull(item.TOTAL_OWE_FEE))+"<hr/>";//接口没有返回该字段
    out += getContent("客户性质：",item.USER_GRADE_NAME)+"<hr/>";
    out += getContent("当前运行状态：",checkNull(item.RUN_NAME))+"<hr/>";
    out += getContent("付费方式：",checkNull(item.PAY_NAME))+"<hr/>";
    out += getContent("信誉度：",item.LIMIT_OWE)+"<hr/>";
    out += getContent("当前预存：",item.PREPAY_FEE)+"<hr/>";
    out += getContent("现金预存：",item.CASH_PREPAY)+"<hr/>";
    out += getContent("天府卡预存：",item.CARD_PREPAY)+"<hr/>";
    out += getContent("其他预存：",item.OTHER_PREPAY)+"<hr/>";
    out += getContent("是否二次入网：",checkNull(item.OPEN_FLAG))+"<hr/>";
    out += getContent("入网时间：",checkNull(item.INNET_TIME))+"<hr/>";
    out += getContent("有效期：",checkNull(item.EXPIRE_TIME))+"<hr/>";
    out += getContent("计费开始时间：",checkNull(item.BEGINFEE_TIME))+"<hr/>";
    out += getContent("本地通话预存：",item.PREPAY_FEE);
  }
  
  return out;
});

var showBusinessVolume = function(outData){
  if(!outData){
    alert("业务量数据为空！");
    return;
  }

  var $tpl = $('#business-volume-tpl');
  var source = $tpl.text();
  var template = Handlebars.compile(source);
  var myData = {
    item: outData
  };

  var html = template(myData);

  $("#business-volume-content").html(html);
};

//营销活动测试数据
var getMarketingList = function(){
  var data = new Array();
  for(var i=0;i<10;i++){
    var detail={};
    detail.ORDER_ID = "01815031200034497";
    detail.MEANS_NAME = "全省数据业务营销活动-Y15Q1-来电提醒+气象通+掌上冲浪-C0S10IN2";
    detail.OPER_NAME = "胡玉蓉";
    detail.OPER_DATE = "2015-03-12 15:45:41";
    detail.ACT_ID = "ADS0";
    // detail.baodijine = "3444";
    // detail.banlishijian = "2015-03-12 15:45:41";
    // detail.baodikaishi = "2015-03-12 15:45:41";
    // detail.baodijiesu = "2018-03-12 15:45:41";

    data.push(detail);
  }

  
  var records = {RECORD:data};

  return {RECORDS:records};
};

var showMarketingActivity = function(outData){
  if(!outData){
    alert("营销活动数据为空！");
    return;
  }

  var records = outData.RECORDS;
  if(!records){
    alert("营销活动数据为空！");
    return;
  }

  var record = records.RECORD;
  if(!record){
    alert("营销活动数据为空！");
    return;
  }
  var $tpl = $('#marketing-activity-tpl');
  var source = $tpl.text();
  var template = Handlebars.compile(source);
  var myData = {
    list: record
  };

  var html = template(myData);

  $("#marketing-list").html(html);
};

/**
营销活动列表进入详情事件
*/
var toDetail = function(orderId){
  console.log("orderId = "+orderId);
  var detail = marketingDetail[orderId];
  console.log(detail);
  var $tpl = $('#marketing-detail-tpl');
  var source = $tpl.text();
  var template = Handlebars.compile(source);
  var myData = {
    item: detail
  };

  var html = template(myData);

  $("#marketing-activity-list").addClass("am-hide");
  $("#marketing-detail").html(html);
  $("#marketing-detail").removeClass("am-hide");
};

/**
营销活动详情返回按钮事件
*/
var toList = function(){
  $("#marketing-detail").addClass("am-hide");
  $("#marketing-activity-list").removeClass("am-hide");
};

/**
显示个人余额基本信息数据
*/
var showPersonalBaseInfo = function(outData){
  if(!outData){
    alert("个人余额基本信息数据为空！");
    return;
  }
  var bInfo = outData.BASE_INFO;
  if(!bInfo){
    alert("个人余额基本信息数据为空！");
    return;
  }
  $("#personal-balance-section").removeClass("am-hide");

  var $tpl = $('#base-info-tpl');
  var source = $tpl.text();
  var template = Handlebars.compile(source);
  var myData = {
    item: bInfo
  };

  var html = template(myData);

  $("#base-info").html(html);
};

/**
构建业务量请求参数
*/
var buildParams = function(){
  var common = {};
  common.PROVINCE_GROUP = "10008";

  var body = {};

  body.WORN_SERV_CODE = "sVpmnMebInfo";
  body.COMMON_INFO = common;
  body.PHONE_NO = phone;
  body.LOGIN_NO = loginNo;

  var params ={};
  params.BODY = body;

  return params;
};

/**
加载业务量数据
*/
var loadBusinessVolume = function(){
  // test data TODO 删除
  // outData = {"CUST_NAME": "V网群成员实例", "SM_NAME": "VPMN", "PHONE_NO": "13708138385", "GRP_NAME": "乐山市中区", "SHORT_NO": "685", "PRCID_NAME": "政企通信管家3元包", "REM_TIME": "600", "GPRS_INFO": "" };
  // showLoadingBar($('#loadingbar-bus-vol'),false);
  // sVpmnMebInfo = outData;
  // showBusinessVolume(sVpmnMebInfo);

  // return;

  var params = buildParams();
  console.log("request:"+JSON.stringify(params));
  var reqUrl = Constants.rpcCrmHost+"sUserOrdQry?token="+getToken();
  sendRestPostAjax(params,reqUrl,showBusinessVolume,"loadingbar-bus-vol");

  // $.ajax({
  //   type: "post",
  //   contentType: "application/json",
  //   data: JSON.stringify(params),
  //   url: Constants.rpcCrmHost+"sUserOrdQry?token="+getToken(),
  //   dataType: "json",
  //   async: true,
  //   headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
  //     showLoadingBar($('#loadingbar-bus-vol'),false);
  //     console.log("data = "+JSON.stringify(data));
  //     var returnData = data.ROOT;
  //     console.info(returnData);
      
  //     if(returnData.RETURN_CODE!=0){
  //       alert(returnData.RETURN_MSG);
  //       console.log("获取RPC接口返回失败！code:"+returnData.RETURN_CODE);
  //       return;
  //     }
      
  //     sVpmnMebInfo = returnData.OUT_DATA;
  //     showBusinessVolume(sVpmnMebInfo);
  //   },
  //   error : function(textStatus) {
  //     showLoadingBar($('#loadingbar-bus-vol'),false);
  //     alert("服务器异常，请联系管理员！");
  //     console.info("request error:");
  //   }
  // });
};

/**
构建业务量请求参数
*/
var buildMarketingParams = function(){

  var requestInfo = {};
  requestInfo.PROVINCE_GROUP = "10008";
  requestInfo.PHONE_NO = phone;
  requestInfo.GROUP_ID = "";

  var body = {};
  body.REQUEST_INFO = requestInfo;
  body.PHONE_NO = phone;

  var params ={};
  params.BODY = body;

  return params;
};

var loadMarketingActivity = function(){
  //TODO 删除
  // var outData = getMarketingList();
  // WsGetActRecord = outData;
  // showLoadingBar($('#loadingbar-mar-act'),false);
  // showMarketingActivity(outData);

  // return;

  //获取列表数据
  var params = buildMarketingParams();
  console.log("request:"+JSON.stringify(params));
  var reqUrl = Constants.rpcCrmHost+"WsGetActRecord?token="+getToken();

  sendRestPostAjax(params,reqUrl,showMarketingActivity,"loadingbar-mar-act");
  // $.ajax({
  //   type: "post",
  //   contentType: "application/json",
  //   data: JSON.stringify(params),
  //   url: Constants.rpcCrmHost+"WsGetActRecord?token="+getToken(),
  //   dataType: "json",
  //   async: true,
  //   headers: {
    //   'token': getParamValue('token'),
    //   'saleType': getParamValue('saleType')
    // },
    // success: function(data) {
    //   if (data.ResultCode === 1009) {
    //     alert('登陆超时，请重新登录！');
    //     jumpToSignin();
    //     return;
    //   }
  //     showLoadingBar($('#loadingbar-mar-act'),false);
  //     console.log("data = "+JSON.stringify(data));
  //     var returnData = data.ROOT;
  //     console.info(returnData);
      
  //     if(returnData.RETURN_CODE!=0){
  //       alert(returnData.RETURN_MSG);
  //       console.log("获取RPC接口返回失败！code:"+returnData.RETURN_CODE);
  //       return;
  //     }
      
  //     showMarketingActivity(returnData.OUT_DATA);
  //   },
  //   error : function(textStatus) {
  //     showLoadingBar($('#loadingbar-mar-act'),false);
  //     alert("服务器异常，请联系管理员！");
  //     console.info("request error:");
  //   }
  // });
};

//测试数据
var getBaseInfo = function(){
  var baseInfo={};
  baseInfo.CUST_NAME = "*亚玲";
  baseInfo.phone = "13518398222";
  baseInfo.city = "广安";
  baseInfo.tctype = "畅聊10元套餐（家园版）";
  baseInfo.wczzd = "2878";
  baseInfo.dqye = "-2788";
  baseInfo.zqf = "2788";
  baseInfo.CUST_Type = "普通";
  baseInfo.oprstatus = "正常";
  baseInfo.payment = "现金/门收";
  baseInfo.xyd = "30000";
  baseInfo.dqyc = "90";
  baseInfo.xjyc = "90";
  baseInfo.tfkyc = "0";
  baseInfo.otheryc = "0";
  baseInfo.issecond = "是";
  baseInfo.rwtime = "2004-06-24 16:30:23";
  baseInfo.yxtime = "20991231";
  baseInfo.begintime = "2004-06-24 16:30:23";
  baseInfo.bdyc = "90";

  return baseInfo;
};

var buildBaseInfoParams = function(){
  var common = {PROVINCE_GROUP:"10008"};
  var body = {};
  body.WORN_SERV_CODE = "sPhConMoreQry";
  body.COMMON_INFO = common;
  body.PHONE_NO = phone;
  body.LOGIN_NO = loginNo;
  body.OP_CODE = "";
  body.CONTRACT_NO = "";
  body.BEGIN_TIME = "";
  body.END_TIME = "";

  return {BODY:body};
};

var loadPersonalBaseInfo = function(){
  //TODO 删除
  // var outData = getBaseInfo();
  // showLoadingBar($('#loadingbar-per-bal'),false);
  // showPersonalBaseInfo(outData);

  // return;

  //TODO获取数据
  var params = buildBaseInfoParams();
  console.log("request:"+JSON.stringify(params));
  var reqUrl = Constants.rpcCrmHost+"sPhConMoreQry?token="+getToken();
  sendRestPostAjax(params,reqUrl,showPersonalBaseInfo,"loadingbar-per-bal");

  // $.ajax({
  //   type: "post",
  //   contentType: "application/json",
  //   data: JSON.stringify(params),
  //   url: Constants.rpcCrmHost+"baseInfo?token="+getToken(),
  //   dataType: "json",
  //   async: true,
  //   headers: {
    //   'token': getParamValue('token'),
    //   'saleType': getParamValue('saleType')
    // },
    // success: function(data) {
    //   if (data.ResultCode === 1009) {
    //     alert('登陆超时，请重新登录！');
    //     jumpToSignin();
    //     return;
    //   }
  //     showLoadingBar($('#loadingbar-per-bal'),false);
  //     console.log("data = "+JSON.stringify(data));
  //     var returnData = data.ROOT;
  //     console.info(returnData);
      
  //     if(returnData.RETURN_CODE!=0){
  //       alert(returnData.RETURN_MSG);
  //       console.log("获取RPC接口返回失败！code:"+returnData.RETURN_CODE);
  //       return;
  //     }
      
  //     baseInfo = returnData.OUT_DATA;
  //     showPersonalBaseInfo(outData);
  //   },
  //   error : function(textStatus) {
  //     showLoadingBar($('#loadingbar-per-bal'),false);
  //     alert("服务器异常，请联系管理员！");
  //     console.info("request error:");
  //   }
  // });
  
};

var loadPersonalBalance = function(){
  //获取基本信息
  loadPersonalBaseInfo();
  //获取账单信息 TODO
};

var hideBusinessVolumeContent = function(isHide){
  if(isHide){
    showLoadingBar($('#loadingbar-bus-vol'),true);
    $("#business-volume-content").addClass("am-hide");
  }else{
    showLoadingBar($('#loadingbar-bus-vol'),false);
    $("#business-volume-content").removeClass("am-hide");
  }
};
var hidePersonalBalanceSection = function(isHide){
  if(isHide){
    showLoadingBar($('#loadingbar-per-bal'),true);
    $("#personal-balance-section").addClass("am-hide");
  }else{
    showLoadingBar($('#loadingbar-per-bal'),false);
    $("#personal-balance-section").removeClass("am-hide");
  }
};
var hideMarketingActivity = function(isHide){
  if(isHide){
    showLoadingBar($('#loadingbar-mar-act'),true);
    $("#marketing-activity-list").addClass("am-hide");
    $("#marketing-detail").addClass("am-hide");
  }else{
    showLoadingBar($('#loadingbar-mar-act'),false);
    $("#marketing-activity-list").removeClass("am-hide");
    //$("#marketing-detail").removeClass("am-hide");
  }
};

$(function() {
  $("#grpName").html(decodeURIComponent(getParamValue("grpName")));
  //alert(window.screen.availHeight);
  //$("#base-info").css({"height":window.screen.availHeight-100});
  $('#general-member').find('a').on('opened.tabs.amui', function(e) {
    console.log('[%s] 选项卡打开了', $(this).text());
    if($(this).attr("href") == "#business-volume"){
      hidePersonalBalanceSection(true);
      hideMarketingActivity(true);
      //业务量
      if(sVpmnMebInfo){
        setTimeout(function(){
          hideBusinessVolumeContent(false);
        },intervalTime);
      }else{
        $("#business-volume-content").removeClass("am-hide");
        loadBusinessVolume();
      }
    }else if($(this).attr("href") == "#marketing-activity"){
      hidePersonalBalanceSection(true);
      hideBusinessVolumeContent(true);

      //营销活动
      if(WsGetActRecord){
        setTimeout(function(){
          hideMarketingActivity(false);
        },intervalTime);
      }else{
        $("#marketing-activity-list").removeClass("am-hide");
        $("#marketing-detail").removeClass("am-hide");
        loadMarketingActivity();
      }
    }else if($(this).attr("href") == "#personal-balance"){
      hideBusinessVolumeContent(true);
      hideMarketingActivity(true);
      //个人余额基本信息
      if(sPhConMoreQry){
        setTimeout(function(){
          hidePersonalBalanceSection(false);
        },intervalTime);
      }else{
        $("#personal-balance-section").removeClass("am-hide");
        loadPersonalBalance();
      }
    }
  });
  
  loadPersonalBalance();
  // var $tpl = $('#persion-tpl'),
  //     tpl = $tpl.text(),
  //     template = Handlebars.compile(tpl),
  //     data = {
  //       accordionData: {
  //         "theme": "basic",
  //         "content": [
  //           {
  //             "title": "客户基本信息",
  //             "content": "内容一",
  //             "active": true
  //           },
  //           {
  //             "title": "账单信息",
  //             "content": "内容二"
  //           }
  //         ]
  //       }
  //     },
  //     html = template(data);

  // $tpl.before(html);

  // $('#myCollapse').collapse();
});